import $store from '@/store'
import uni_request from '@/common/js/uni_request/uni_request.js'
import { baseUrl } from '@/common/js/config.js'

const request = uni_request({
	baseURL:baseUrl(),
	timeout:5000
})

request.interceptors.request.use(async (config, ...args) => { // 请求拦截器
	// ...
	if ($store.state.token) {
		// await new Promise(resolve => ))
		config.header.Authorization = 'Bearer ' + $store.state.token // 把 token 放在请求头
	}
	
	return config
})


request.interceptors.response.use( response => { // 响应拦截器
	
	let statusCode = response.statusCode
	if(statusCode == 200){
		let data = response.data
		if(typeof data === 'string'){
			data = JSON.parse(data)
		}
		switch(data.code){
			case 200:
				return Promise.resolve(data)
				break
			case 400:
				uni.showToast({
					title:data.message,
					icon:'none'
				})
				return Promise.reject(data)
				break
			case 405:
				return Promise.reject(data)
				break
			case 406:
				uni.showToast({
					title:data.message,
					icon:'none'
				})
				return Promise.reject(data)
				break
			default:
				uni.showToast({
					title:'请求失败',
					icon:'none'
				})
				return Promise.reject(data)
				break
		}
	}else{
		uni.showToast({
			title:'请求失败',
			icon:'none'
		})
		return Promise.reject(response.data)
	}
	//return response
})

request.onerror = (...args) => {
	uni.showToast({
		title:args[3].indexOf('超时取消') != -1 ? '请求超时' : '请求失败',
		icon:'none'
	})
} // 错误监听

export default request
